package com.idas.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionHandler {
	protected static String conStr;
	protected static String user;
	protected static String password;

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	/**
	 *initialise the DB This must be called as the first line of code in the
	 * main function
	 */
	public static void initDBhandler() {
		conStr = "jdbc:mysql://" + System.getProperty("DB_SERVER") +"/"+  System.getProperty("DB_NAME");		
		user = System.getProperty("DB_USER");
		password = System.getProperty("DB_PASSWD");		
	}

	/**
	 * Returns a SQL connection. Each connection is a transactional connection
	 * 
	 * @return
	 * @throws SQLException
	 */
	public static Connection getClusterConnection() throws SQLException {
		Connection conn = DriverManager.getConnection(conStr, user, password);
		conn.setAutoCommit(false);
		return conn;
	}
	
	public static Connection getNoTransactionConnection() throws SQLException {
		Connection conn = DriverManager.getConnection(conStr, user, password);
		conn.setAutoCommit(true);
		return conn;
	}
	
	
	/**
	 * End the transactional connection
	 * @param conn : The SQL Connection 
	 * @param commit : if true commit all the changes, false will be a rollback
	 * @throws SQLException
	 */
	public static void endConnection(Connection conn, boolean commit)
	throws SQLException {

		if (conn != null) {
			try {
				if( conn.getAutoCommit() == false ) {
					if (commit) {
						conn.commit();
					} else {
						conn.rollback();
					}
				}
			} finally {
				conn.close();
			}
		}
	}
	

}